package com.example.springbootdemo.handler;

import com.example.springbootdemo.exception.BusinessErrorException;
import com.example.springbootdemo.exception.BusinessResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败会被调用
 * @author hh
 * @date 2022/1/27
 */
@Slf4j
@Component
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (exception instanceof AccountExpiredException) {
            // 账号过期
            // log.info("[登录失败] - 用户[{}]账号过期", username);
            throw new BusinessErrorException(BusinessResponseEnum.USER_ACCOUNT_EXPIRED);

        } else if (exception instanceof BadCredentialsException) {
            // 密码错误
            // log.info("[登录失败] - 用户[{}]密码错误", username);
            throw new BusinessErrorException(BusinessResponseEnum.USER_PASSWORD_ERROR);

        } else if (exception instanceof CredentialsExpiredException) {
            // 密码过期
            // log.info("[登录失败] - 用户[{}]密码过期", username);
            throw new BusinessErrorException(BusinessResponseEnum.USER_PASSWORD_EXPIRED);

        } else if (exception instanceof DisabledException) {
            // 用户被禁用
            // log.info("[登录失败] - 用户[{}]被禁用", username);
            throw new BusinessErrorException(BusinessResponseEnum.USER_DISABLED);

        } else if (exception instanceof LockedException) {
            // 用户被锁定
            // log.info("[登录失败] - 用户[{}]被锁定", username);
            throw new BusinessErrorException(BusinessResponseEnum.USER_LOCKED);

        } else if (exception instanceof InternalAuthenticationServiceException) {
            // 内部错误
            // log.error(String.format("[登录失败] - [%s]内部错误", username), exception);
            throw new BusinessErrorException(BusinessResponseEnum.USER_LOGIN_FAIL);

        } else {
            // 其他错误
            // log.error(String.format("[登录失败] - [%s]其他错误", username), exception);
            throw new BusinessErrorException(BusinessResponseEnum.USER_LOGIN_FAIL);
        }
    }

}
